package com.wang.tool.okhttp;

import com.alibaba.fastjson.JSONObject;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

class Demo {


    public static void main(String[] args) throws ExecutionException, InterruptedException {


        String result = HttpTemplate.get("localhost:70/hi");



//       post方式 json body
        JSONObject body = new JSONObject();
        body.put("参数", "值");
        result = HttpTemplate.jsonPost("localhost:70/hi", body);




//        post sse模型 异步api
        Future<String> future = HttpTemplate.sse("localhost:70/hi", 30000, new SseHandler<String>() {
            @Override
            public void fillRequest(Request.Builder builder) {

            }

            @Override
            public void onReadLine(String line) {
                System.out.println("读了一行了");
            }

            @Override
            public String onFinished() {
                System.out.println("结束了");
                return "结束了";
            }

            @Override
            public String onError(Throwable error) {
                return null;
            }
        });

//        等结果
        String s = future.get();



//        异步api，自定义http
        CompletableFuture<String> asyncHttp = HttpTemplate.async("localhost", 10000,new HttpHandler<String>() {

            @Override
            public void fillRequest(Request.Builder builder) {
                builder.addHeader("ceshi", "va");
            }

            @Override
            public String read(Response response) throws IOException {
                return null;
            }

            @Override
            public String onError(Throwable error) throws Throwable {
                return null;
            }
        });


        Iterator<String> generator = buildGentor();


        while (generator.hasNext()){
            String o = generator.next();
            System.out.println("结果"+o);
//          生成器结果解析
        }
        System.out.println("jieshule");

    }

    public static Iterator<String> buildGentor() {

        SimpleGenerator<String> queue = new SimpleGenerator<>();
        new Thread(() -> {

            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                queue.push("111" + i);
                if (i==5) {
                    queue.markEnd();
                }
            }
        }).start();
        return queue.iterator();
    }

}